/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.peng.commdit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.peng.commdit.domain.CommodityManage;
import me.peng.commdit.domain.CommodityOrder;
import me.peng.domain.RecyclerUser;
import me.peng.domain.RecyclercdsRecord;
import me.peng.domain.config.SysResult;
import me.peng.domain.mapper.CommdityOrderMapper;
import me.peng.domain.mapper.CommoditMapper;
import me.peng.domain.mapper.DsRecordMapper;
import me.peng.domain.mapper.RecyclerUserMpper;
import me.peng.utils.ValidationUtil;
import me.peng.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.peng.commdit.repository.CommodityOrderRepository;
import me.peng.commdit.service.CommodityOrderService;
import me.peng.commdit.service.dto.CommodityOrderDto;
import me.peng.commdit.service.dto.CommodityOrderQueryCriteria;
import me.peng.commdit.service.mapstruct.CommodityOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.peng.utils.PageUtil;
import me.peng.utils.QueryHelp;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author pengjianye
* @date 2021-10-08
**/
@Service
@RequiredArgsConstructor
public class CommodityOrderServiceImpl implements CommodityOrderService {

    private final CommodityOrderRepository commodityOrderRepository;
    private final CommodityOrderMapper commodityOrderMapper;

    @Override
    public Map<String,Object> queryAll(CommodityOrderQueryCriteria criteria, Pageable pageable){
        Page<CommodityOrder> page = commodityOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(commodityOrderMapper::toDto));
    }

    @Override
    public List<CommodityOrderDto> queryAll(CommodityOrderQueryCriteria criteria){
        return commodityOrderMapper.toDto(commodityOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CommodityOrderDto findById(Integer id) {
        CommodityOrder commodityOrder = commodityOrderRepository.findById(id).orElseGet(CommodityOrder::new);
        ValidationUtil.isNull(commodityOrder.getId(),"CommodityOrder","id",id);
        return commodityOrderMapper.toDto(commodityOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommodityOrderDto create(CommodityOrder resources) {
        return commodityOrderMapper.toDto(commodityOrderRepository.save(resources));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CommodityOrder resources) {
        CommodityOrder commodityOrder = commodityOrderRepository.findById(resources.getId()).orElseGet(CommodityOrder::new);
        ValidationUtil.isNull( commodityOrder.getId(),"CommodityOrder","id",resources.getId());
        commodityOrder.copy(resources);
        commodityOrderRepository.save(commodityOrder);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            commodityOrderRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CommodityOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CommodityOrderDto commodityOrder : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户编号", commodityOrder.getParentId());
            map.put("地址id", commodityOrder.getAddressId());
            map.put("地址信息", commodityOrder.getAddressinfo());
            map.put("订单编号", commodityOrder.getOrdernum());
            map.put("订单状态", commodityOrder.getStatus());
            map.put("订单信息", commodityOrder.getOrderinfo());
            map.put("购买商品数", commodityOrder.getNunber());
            map.put("运费", commodityOrder.getFreight());
            map.put("实付价格", commodityOrder.getPrice());
            map.put("创建时间", commodityOrder.getCreateDate());
            map.put("实付积分", commodityOrder.getPaidpoint());
            map.put("商品id", commodityOrder.getCommid());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Autowired
    CommdityOrderMapper OrderMapper;
    @Autowired
    RecyclerUserMpper recyclerUserMpper;
    /**
     * 根据用户id查询用户所有订单
     * @param parentId
     * @return
     */
    @Override
    public SysResult getCommdityOrder(Integer parentId) {
        QueryWrapper<CommodityOrder> queryWrapper = new QueryWrapper<>();
        //selec * from recycler_address where parent_id=pareiId
        queryWrapper.eq("parent_id", parentId);
        List<CommodityOrder> list = OrderMapper.selectList(queryWrapper);
        return SysResult.success(list);
    }
    /**
     * 提交订单数据到数据库
     * @param commodityOrder
     * @return
     */
    @Autowired
    CommoditMapper commoditMapper;

    @Override
    public SysResult postCommdityOrder(CommodityOrder commodityOrder) {

        //去修改商品库存
        //用户已经支付积分为待发货状态
        if (commodityOrder.getStatus()!=null&&"待发货".equals(commodityOrder.getStatus())){
            //购买商品数
            int commnumber = Integer.parseInt(commodityOrder.getNunber());
            //根据商品id查询当前库存
            CommodityManage commodityManage =commoditMapper.selectById(commodityOrder.getCommid());
            //当前库存必须大于或者等于购买数量
            if (commodityManage.getInsock()>=Integer.parseInt(commodityOrder.getNunber())){
                int commid=commodityOrder.getCommid();
                //商品库存-用户购买数量
                int kucun=commodityManage.getInsock()-commnumber;
                //当前已售+用户当前购买数
                int sold=commodityManage.getProductSold()+commnumber;
                //更新商品库存
                commoditMapper.updateById(new CommodityManage().setId(commid).setInsock(kucun).setProductSold(sold));

                /************扣除积分**********/
                //获取实付积分
                int paidpoint=commodityOrder.getPaidpoint();
                //用户id查询用户积分值
                RecyclerUser recyclerUserObj=recyclerUserMpper.selectById(commodityOrder.getParentId());
                //用户积分
                int point=recyclerUserObj.getPoint();
                //用户积分>=实付积分---更新用户积分
                if (point>=paidpoint){
                    recyclerUserMpper.updateById(new RecyclerUser()
                                     .setId(commodityOrder.getParentId())
                                        //用户积分减去实付积分
                                     .setPoint(point-paidpoint));

                    //插入积分记录
                    RecyclercdsRecord recyclercdsRecord= new RecyclercdsRecord();
                    //从订单中获取记录
                    recyclercdsRecord.setParentId(recyclerUserObj.getId());
                    recyclercdsRecord.setUname(recyclerUserObj.getUsername());
                    //
                    recyclercdsRecord.setRtitle("商品兑换");
                    recyclercdsRecord.setType("积分");
                    recyclercdsRecord.setCoreditnum("-"+paidpoint);
                    Date date = new Date();
                    recyclercdsRecord.setCreatedate(new Timestamp(date.getTime()));
                    postInsideCreditsRecord(recyclercdsRecord);
                }

            }
        }

        OrderMapper.insert(commodityOrder);
        return SysResult.success();
    }


    @Autowired
    DsRecordMapper dsRecordMapper;

    //积分记录
    public void postInsideCreditsRecord(RecyclercdsRecord recyclercdsRecord) {

        dsRecordMapper.insert(recyclercdsRecord);
        System.out.println("ComodityOrderServiceIlmp/postInsideCreditsRecord------------------------------------------>积分记录插入成功");

    }


    /**
     * deleteOrder
     * @param id
     * @return
     */
    @Override
    public SysResult deleteCommdityOrder(Integer id) {
        OrderMapper.deleteById(id);
        return SysResult.success();
    }

    //修改订单信息---状态---商品库存---积分
    @Override
    public SysResult putCommdityOrder(CommodityOrder commodityOrder) {

        //取消订单，判断当前订单处于什么状态，待发货状态需要退回积分----修改商品库存
        if (commodityOrder.getStatus()!=null&&"订单取消".equals(commodityOrder.getStatus())){
            //查询当前订单状态
            CommodityOrder comm=getByIdInfo(commodityOrder.getId());
            if ("待发货".equals(comm.getStatus())){
                //用户id
                int comParetId=comm.getParentId();
                RecyclerUser recyclerUser=recyclerUserMpper.selectById(comParetId);
                //实付积分+用户积分
                int commPoint=comm.getPaidpoint()+recyclerUser.getPoint();
                //退还积分
                recyclerUserMpper.updateById(new RecyclerUser().setId(comParetId).setPoint(commPoint));

                 /********库存业务操作************/
                //根据订单id查询订单数据
                CommodityOrder commoOrder=OrderMapper.selectById(commodityOrder.getId());
                //商品对象//商品id-commid
                CommodityManage commodityManage =commoditMapper.selectById(commoOrder.getCommid());
                //获取用户购买商品数量
                int order=Integer.parseInt(commoOrder.getNunber());
                //商品库存
                int insock=commodityManage.getInsock()+order;
                //已售商品数量
                int sold=commodityManage.getProductSold()-order;
                //商品id
                Integer commid = commoOrder.getCommid();

                //更新商品库存
                commoditMapper.updateById(new CommodityManage().setId(commid).setInsock(insock).setProductSold(sold));

                //退还积分记录
                RecyclercdsRecord recyclercdsRecord= new RecyclercdsRecord();
                //从订单中获取记录
                recyclercdsRecord.setParentId(recyclerUser.getId());
                recyclercdsRecord.setUname(recyclerUser.getUsername());
                //
                recyclercdsRecord.setRtitle("订单取消");
                recyclercdsRecord.setType("积分");
                //实付积分
                recyclercdsRecord.setCoreditnum("退回积分+"+comm.getPaidpoint());
                Date date = new Date();
                recyclercdsRecord.setCreatedate(new Timestamp(date.getTime()));
                postInsideCreditsRecord(recyclercdsRecord);


            }
        }
        //去修改商品库存
        //用户已经支付积分为待发货状态
        if (commodityOrder.getStatus()!=null&&"待发货".equals(commodityOrder.getStatus())){
            //根据订单id查询到当前订单所有信息
            CommodityOrder orderObj=OrderMapper.selectById(commodityOrder.getId());

            //用户id
            int comParetId=orderObj.getParentId();
            RecyclerUser recyclerUser=recyclerUserMpper.selectById(comParetId);

            //用户积分>=实付积分
            if (recyclerUser.getPoint()>=orderObj.getPaidpoint()){
                //用户积分-实付积分
                int commPoint=recyclerUser.getPoint()-orderObj.getPaidpoint();
                //扣除积分
                recyclerUserMpper.updateById(new RecyclerUser().setId(comParetId).setPoint(commPoint));

                //退还积分记录
                RecyclercdsRecord recyclercdsRecord= new RecyclercdsRecord();
                //从订单中获取记录
                recyclercdsRecord.setParentId(recyclerUser.getId());
                recyclercdsRecord.setUname(recyclerUser.getUsername());
                //
                recyclercdsRecord.setRtitle("积分兑换");
                recyclercdsRecord.setType("积分");
                //实付积分
                recyclercdsRecord.setCoreditnum("-"+orderObj.getPaidpoint());
                Date date = new Date();
                recyclercdsRecord.setCreatedate(new Timestamp(date.getTime()));
                postInsideCreditsRecord(recyclercdsRecord);
            }
            //购买商品数
            int commnumber = Integer.parseInt(orderObj.getNunber());
            //根据商品id查询当前库存
            CommodityManage commodityManage =commoditMapper.selectById(orderObj.getCommid());
            //当前库存必须大于或者等于购买数量
            if (commodityManage.getInsock()>=Integer.parseInt(orderObj.getNunber())){
                //此乃商品管理id---->commid
                int commid=orderObj.getCommid();
                //商品库存-用户购买数量
                int kucun=commodityManage.getInsock()-commnumber;
                //当前已售+用户当前购买数
                int sold=commodityManage.getProductSold()+commnumber;
                //根据商品管理id---->更新商品库存
                commoditMapper.updateById(new CommodityManage().setId(commid).setInsock(kucun).setProductSold(sold));
            }
        }

        OrderMapper.updateById(commodityOrder);
        return SysResult.success();

    }

    /**
     * 根据用户订单号查询当前订单
     * @param ordernumber
     * @return
     */
    @Override
    public SysResult getOrdernumber(String ordernumber) {
        QueryWrapper<CommodityOrder> queryWrapper = new QueryWrapper<>();
        //selec * from recycler_address where parent_id=pareiId
        queryWrapper.eq("ordernum", ordernumber);
        List<CommodityOrder> list = OrderMapper.selectList(queryWrapper);
        return SysResult.success(list);
    }


    public CommodityOrder getByIdInfo(Integer id) {

        return OrderMapper.selectById(id);
    }

}
